<?php
/*
 * 修改当前登录用户密码
 */
require_once 'auth.php';
requireLogin();

// 初始化消息变量
$message = '';
//从session 获取用户名
$username = $_SESSION['username'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 从 POST 请求中获取用户输入的旧密码、新密码和确认密码
    $oldPassword = $_POST['old_password'];
    $newPassword = $_POST['new_password'];
    $confirmPassword = $_POST['confirm_password'];

    //如果新密码和确认密码不一致，提示用户
    if ($newPassword !== $confirmPassword) {
        $message = '新密码和确认密码不一致';
    } else {
        // 验证用户名密码是否正确
        if (login($username,  $oldPassword)) {
            //更新密码
            $conn = dbConnect();
            $stmt = $conn->prepare('UPDATE users SET password =? WHERE username =?');
            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt->bind_param('ss', $hashedPassword, $username);
            $stmt->execute();
            $message = '密码已修改';
        } else {
            $message = '用户名或密码错误';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改密码</title>
    <link rel="stylesheet" href="dist/css/tabler.min.css">
</head>

<body class="layout-fluid layout-vertical">
    <?php include 'navbar.php'; ?>
    <div class="page">
        <div class="container-fluid">
            <h1>修改密码</h1>
            <form method="post">
                <div class="form-group">
                    <label for="username"><?= htmlspecialchars($message) ?></label>
                </div>
                <div class="form-group">
                    <label for="old_password">旧密码</label>
                    <input type="password" class="form-control" id="old_password" name="old_password" required>
                </div>
                <div class="form-group">
                    <label for="new_password">新密码</label>
                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                </div>
                <div class="form-group">
                    <label for="confirm_password">确认新密码</label>
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                </div>
                <button type="submit" class="btn btn-primary">修改密码</button>
            </form>
        </div>
    </div>
    <script src="dist/js/tabler.min.js"></script>
</body>

</html>